from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class AreasView(View):
    def get(self, request):
        # 查询缓存
        provinces_list = cache.get('provinces')
        # 无缓存：查询数据库并保存数据
        if provinces_list is None:
            # 查询数据库
            provinces = Area.objects.filter(parent=None)
            provinces_list = []
            for provinces in provinces:
                provinces_list.append({
                    'id': provinces.id,
                    'name': provinces.name,
                })
            # 保存缓存
            cache.set('provinces', provinces_list, 24*3600)
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': provinces_list})
        pass


class SubAreasView(View):
    def get(self, request, id):
        # 查询缓存
        subs_list = cache.get('subs_list_%s'%id)
        # 无缓存：查询数据库并保存数据
        if subs_list is None:
            subs = Area.objects.get(id=id)

            subs_list = []
            for i in subs.subs.all():
                subs_list.append({
                    'id': i.id,
                    'name': i.name,
                })
            cache.set('subs_list_%s'%id, subs_list, 24 * 3600)
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': {'subs': subs_list}})
